package top.truehaku.generator.common.util;





public class JdbcHelper {

    /**
     * 通过url获取数据库名称
     * @param jdbcUrl
     * @return
     */
    public static String getTableSchema(String jdbcUrl) {
        String database = null;
        int pos, pos1;
        String connUri;
        if (StringUtils.isBlank(jdbcUrl)){
            throw new IllegalArgumentException("Invalid JDBC url.");
        }
        jdbcUrl = jdbcUrl.toLowerCase();
        if (jdbcUrl.startsWith("jdbc:impala")) {
            jdbcUrl = jdbcUrl.replace(":impala", "");
        }
        if (!jdbcUrl.startsWith("jdbc:")
                || (pos1 = jdbcUrl.indexOf(':', 5)) == -1) {
            throw new IllegalArgumentException("Invalid JDBC url.");
        }
        connUri = jdbcUrl.substring(pos1 + 1);
        if (connUri.startsWith("//")) {
            if ((pos = connUri.indexOf('/', 2)) != -1) {
                database = connUri.substring(pos + 1);
            }
        } else {
            database = connUri;
        }
        if (database.contains("?")) {
            database = database.substring(0, database.indexOf("?"));
        }
        if (database.contains(";")) {
            database = database.substring(0, database.indexOf(";"));
        }
        if (StringUtils.isBlank(database)) {
            throw new IllegalArgumentException("Invalid JDBC url.");
        }
        return database;
    }

}
